package org.cainiao.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioServer {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("Server listening on port 8080...");
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeySet = selector.selectedKeys();
            if (!selectionKeySet.isEmpty()) {
                Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
                while (selectionKeyIterator.hasNext()) {
                    SelectionKey selectionKey = selectionKeyIterator.next();
                    selectionKeyIterator.remove();
                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = server.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        System.out.println("Client connected.");
                    } else if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // I/O 输入，即读，是从通道向缓冲区填入数据
                        int bytesRead = socketChannel.read(buffer);
                        if (bytesRead == -1) {
                            socketChannel.close();
                            System.out.println("Client disconnected.");
                        } else {
                            buffer.flip();
                            byte[] data = new byte[buffer.remaining()];
                            // 这里的正确性的前提是，buffer 足够大，或者运气足够好，没有将字符截断
                            buffer.get(data);
                            // String 构造器默认使用 UTF-8 解码字节数组
                            String request = new String(data);
                            System.out.println("Received from client: " + request);
                            String response = "Hello, Client!\n";
                            // String.getBytes() 默认使用 UTF-8 编码字节数组
                            ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
                            // I/O 输出，即写，是从缓冲区向通道倒出数据
                            socketChannel.write(responseBuffer);
                        }
                    }
                }
            } else {
                // TODO 因为是非阻塞的，为了避免忙等浪费 CPU 资源，这里可以做一些任务
            }
        }
    }
}
